// map.js
Page({
  data: {
    latitude: 30.707416,
    longitude: 114.40093,
    repairDetail: {},
    markers: [
      {
        // 传智的位置
        latitude: 30.707416,
        longitude: 114.40093,
        width: 50,
        height: 50,
        id: 1,
        iconPath: '/static/images/marker.png'
      },
      {
        // 武湖新天地的位置
        latitude: 30.706209,
        longitude: 114.410605,
        width: 20,
        height: 30,
        id: 2
      }
    ],
    polyline: []
  },
  onLoad({ id }) {
    // 获取报修详情的数据
    this.getRepairDetail(id)
    // 进行路线规划
    this.getPolyline()
  },
  getPolyline() {
    wx.qqMap.direction({
      mode: 'bicycling', // 骑行
      from: {
        latitude: 30.707416,
        longitude: 114.40093,
      },
      to: {
        latitude: 30.706209,
        longitude: 114.410605,
      },
      success: res => {
        console.log(res)

        let coors = res.result.routes[0].polyline, points = [];
        //坐标解压（返回的点串坐标，通过前向差分进行压缩）
        let kr = 1000000;
        for (let i = 2; i < coors.length; i++) {
          coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
        }
        //将解压后的坐标放入点串数组points中
        for (let i = 0; i < coors.length; i += 2) {
          points.push({ latitude: coors[i], longitude: coors[i + 1] })
        }

        // console.log(points)

        this.setData({
          latitude: points[25].latitude, // 地图中心点
          longitude: points[25].longitude,
          polyline: [ // 路线
            {
              points,
              color: '#0f0',
              width: 4
            }
          ],
          markers: [ // 标记点
            {
              // 师傅的位置
              latitude: points[25].latitude,
              longitude: points[25].longitude,
              width: 50,
              height: 50,
              id: 1,
              iconPath: '/static/images/marker.png'
            },
            {
              // 武湖新天地的位置
              latitude: 30.706209,
              longitude: 114.410605,
              width: 20,
              height: 30,
              id: 2
            }
          ],
        })
      }
    })
  },
  // 报修详情接口
  async getRepairDetail(id) {
    if (!id) return wx.utils.toast('参数有误!')
    // 调用接口
    const { code, data: repairDetail } = await wx.http.get('/repair/' + id)
    // 检测接口是否调用成功
    if (code !== 10000) return wx.utils.toast()
    // 渲染数据
    this.setData({ repairDetail })
  },
  editRepair() {
    wx.navigateTo({
      url: '/repair_pkg/pages/form/index?id=' + this.data.repairDetail.id
    })
  },
  async cancelRepair() {
    // 发请求取消
    const { code } = await wx.http.put(`/cancel/repaire/${this.data.repairDetail.id}`)
    if (code !== 10000) return wx.utils.toast('取消失败')
    // 如果取消成功了, 返回到列表页
    wx.navigateBack()
  }
})
